//
//  SWTransactionManager.swift
//  ChildStory
//  交易管理
//  Created by linhan on 2017/1/10.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation

class SWPageProduct
{
    var page:SWPage
    var selected:Bool = false
    
    init(page:SWPage)
    {
        self.page = page
    }
    
}

private let _manager:SWTransactionManager = SWTransactionManager()
class SWTransactionManager: NSObject,SWAPIComponent
{
    private var _dataPath:String = ""
    private var _records:[SWOrderRecord] = []
    
    class func sharedManager() -> SWTransactionManager
    {
        return _manager
    }
    
    override init() {
        super.init()
        
        //支付成功
        SWNotificationCenter.addObserver(self, selector: #selector(paySuccessNotification), name: NotificationName.PaySuccess, object: nil)
        //单张上传完成
        SWNotificationCenter.addObserver(self, selector: #selector(pageUploadCompleteNotification(_:)), name: NotificationName.PageUploadComplete, object: nil)
        
        //全部上传完成
        SWNotificationCenter.addObserver(self, selector: #selector(pageUploadAllCompleteNotification(_:)), name: NotificationName.PageUploadAllComplete, object: nil)
        
        //监听网络状态
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged), name: NSNotification.Name.SWNetworkMonitorReachableWiFi, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged), name: NSNotification.Name.SWNetworkMonitorNotReachable, object: nil)
        
        _dataPath = "\(SWBookManager.sharedManager().baseDirectory)/orderpage.data"
        _records = SWCacheManager.sharedManager().readCache(_dataPath) as? [SWOrderRecord] ?? []
        
        for record in _records
        {
            //有效订单，但未上传完成的继续上传
            if record.unuploadedPages.count > 0
            {
                //orderUploadUpdateHander(record)
                SWUploadManager.sharedManager().upload(record: record, rightNow: false)
            }
            
        }
        
        networkStatusChanged()
        
    }
    
    @objc private func networkStatusChanged()
    {
        //如果是WIFI网络下，进行上传
        let status = SWNetworkMonitor.sharedMonitor().status
        trace("SWNetworkStatus:", status.rawValue)
        if status == SWNetworkStatus.WiFi
        {
            SWUploadManager.sharedManager().uploadAll()
        }
        else if status == SWNetworkStatus.notReachable
        {
            SWUploadManager.sharedManager().pauseAll()
        }
    }
    
    //购物篮中的页面
    private var _pageCount:Int = 0
    var pages:[SWPageProduct] = []
    {
        didSet{
            if pages.count != _pageCount
            {
                _pageCount = pages.count
                SWNotificationCenter.post(name: NotificationName.PageProductCountChanged)
                
                
            }
        }
    }
    
    func launch()
    {
        
    }
    
    //添加到购物篮
    func addToBasket(page:SWPageProduct)
    {
        if !pages.contains(where: {($0.page.pageID ?? "") == (page.page.pageID ?? "")})
        {
            pages.append(page)
        }
    }
    
    //从购物篮中移除
    func removeFromBasket(page:SWPageProduct)
    {
        if let index = pages.index(where: {($0.page.pageID ?? "") == (page.page.pageID ?? "")})
        {
            pages.removeAtIndexSafely(index)
        }
        
    }
    
    //清空购物篮
    func clearBasket()
    {
        pages.removeAll()
    }
    
    //购物篮中是否有某个页面
    func basketContains(page:SWPageProduct) -> Bool
    {
        return pages.contains(where: {($0.page.pageID ?? "") == (page.page.pageID ?? "")})
    }
    
    //提交订单
    func submitOrder(addresseeInfo:SWAddresseeInfo, product:Any, successCallback:@escaping ((SWPurchaseRequisition)->Void), failCallback:@escaping ((NSError)->Void))
    {
        let req = SWOrderCreateReq()
        req.addressID = addresseeInfo.addressID
        req.count = 1
        req.remark = ""
        req.successCallback = {[weak self] response,_ in
            if let requisitionRsp = (response as? SWOrderCreateRsp)?.requisition,
                let requisition = SWPurchaseRequisition(response: requisitionRsp)
            {
                successCallback(requisition)
                //订单创建成功后，生成合成图到订单ID下
                if requisition.orderID != ""
                {
                    self?.addToRecord(orderID: requisition.orderID)
                }
            }
            else
            {
                failCallback(SWError.DefaultNetworkError)
            }
        }
        req.failCallback = { error in
            failCallback(error)
        }
        load(req)
    }
    
    //上传订单
    func uploadOrder(orderID:String)
    {
        if let index = _records.index(where: {($0.orderID ?? "") == orderID}),
           let record = _records.valueAt(index)
        {
            SWUploadManager.sharedManager().upload(record: record, rightNow: true)
        }
    }
    
    private func addToRecord(orderID:String)
    {
        if !_records.contains(where: {($0.orderID ?? "") == orderID})
        {
            var clonePages:[SWPage] = []
            for item in pages
            {
                let page:SWPage = item.page
                if let clonePage = page.copy() as? SWPage
                {
                    clonePage.orderID = orderID
                    clonePages.append(clonePage)
                    
                }
            }
            let record:SWOrderRecord = SWOrderRecord()
            record.orderID = orderID
            record.pages = clonePages
            _records.append(record)
            save()
            
            print("clonePages:", clonePages.count)
            
            //加入任务列表，等待支付完成
            SWUploadManager.sharedManager().upload(record: record, rightNow: false)
            
            //orderUploadUpdateHander(record)
            
        }
    }
    
    private func save()
    {
        SWCacheManager.sharedManager().writeCache(_records, path: _dataPath)
    }
    
    
    //支付后进行上传
    @objc private func paySuccessNotification(_ notification:Notification)
    {
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,
           let index = _records.index(where: {($0.orderID ?? "") == orderID}),
           let record = _records.valueAt(index)
        {
            record.valid = true
            save()
            if SWNetworkMonitor.sharedMonitor().status == .cellular
            {
                Alert.show("", message: "3G/4G网络下是否上传", buttons: ["是","否"], closeHandler: {[weak self] index in
                    //self?.orderUploadUpdateHander(record, uploadRightNow:index == 0)
                    SWUploadManager.sharedManager().upload(record: record, rightNow: index == 0)
                })
            }
            else
            {
                //orderUploadUpdateHander(record, uploadRightNow:true)
                SWUploadManager.sharedManager().upload(record: record, rightNow: true)
            }
            
        }
    }
    
    @objc private func pageUploadCompleteNotification(_ notification:Notification)
    {
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,
            _records.contains(where: {($0.orderID ?? "") == orderID})
        {
            save()
        }
    }
    
    
    
    //全部上传完成
    @objc private func pageUploadAllCompleteNotification(_ notification:Notification)
    {
        print("全部上传完成")
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,
            let index = _records.index(where: {($0.orderID ?? "") == orderID}),
            let record = _records.valueAt(index)
        {
            SWUploadManager.sharedManager().upload(record: record, rightNow: true)
            SWUploadManager.sharedManager().removeUploader(id: orderID)
        }
    }
    
    
}
